package com.digitalchina.filter;

import com.digitalchina.user.model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 添加登录过滤
 *
 * Created by zhouxiaa on 2017/7/14.
 */
@WebFilter(filterName = "LoginFilter" , urlPatterns ="/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)  throws IOException, ServletException{//
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        System.out.println(request.getServletPath());
        if((!request.getServletPath().endsWith(".do")&&!request.getServletPath().endsWith(".html"))||request.getServletPath().equals("/login.html")){
            chain.doFilter(servletRequest, servletResponse);
        }else{
            if(null != session){
                User userInfo = (User) session.getAttribute("userInfo");
                if(null != userInfo){
                    chain.doFilter(servletRequest, servletResponse);
                }else{
                    if(request.getServletPath().equals("/goLogin.do")){
                        chain.doFilter(servletRequest, servletResponse);
                    }else {
                        response.sendRedirect(request.getContextPath() + "/login.html");
                    }
                }
            }else{
                if(request.getServletPath().equals("/goLogin.do")){
                    chain.doFilter(servletRequest, servletResponse);
                }else {
                    response.sendRedirect(request.getContextPath() + "/login.html");
                }
            }
        }

    }

    @Override
    public void destroy() {

    }
}
